﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//
using System.IO;
using System.Collections;
using System.Diagnostics;
/*
Copyright 2010 Mirosław M. Mączka

This file is part of Flac2Wma.

    Flac2Wma is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Foobar is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/
namespace Flac2Wma
{
    internal class Handler_AAC : IOutputHandler
    {
        //http://www.nero.com/enu/company/about-nero/nero-aac-codec.php
        //
        public bool DeleteInputFile { get; set; }
        //
        public string InputFileName { get; set; }
        public string OutputFileName { get; set; }
        public string OutputFileNameExtension { get { return ".mp4"; } }
        public string OutputFileType { get { return "AAC"; } }
        //
        public string Author { get; set; }
        public string Copyright { get; set; }
        public string Description { get; set; }
        public string Rating { get; set; }
        public string Title { get; set; }
        //
        public string AlbumTitle { get; set; }
        public string Genre { get; set; }
        public int TrackNumber { get; set; }
        public int Year { get; set; }
        public string Composer { get; set; }
        public object MCDI { get; set; }
        //
        public string ErrorMessage { get; set; }
        public string DefaultDownloadPage { get { return "http://www.nero.com/enu/company/about-nero/nero-aac-codec.php"; } }
        //
        //
        public int PlayTime { get; set; }
        //
        public Handler_AAC()
        {
            ClearProps();
            //
        }
        //
        public void ClearProps()
        {
            Author = string.Empty;
            Copyright = string.Empty;
            Description = string.Empty;
            Rating = string.Empty;
            Title = string.Empty;
            //
            AlbumTitle = string.Empty;
            Genre = string.Empty;
            TrackNumber = -1;
            Year = -1;
            Composer = string.Empty;
            MCDI = null;
        }
        //
        //
        //public string AAC_Encoder { get; set; }
        //public string AAC_CommandLine { get; set; }
        //  AAC_Encoder = @"C:\Apps\bin\neroAacEnc.exe";
        // AAC_CommandLine = "-q 0.62  -if \"{0}\" -of \"{1}\"";

        //
        public bool Do(string wavPathName, string outputDirectory)
        {
            //string output = "";
            int iExitCode = -1;
            //
            //
            if (null != outputDirectory)
            {
                OutputFileName = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(wavPathName) + OutputFileNameExtension);
            }
            else
            {
                OutputFileName = Path.Combine(Path.GetDirectoryName(wavPathName), Path.GetFileNameWithoutExtension(wavPathName) + OutputFileNameExtension);
            }
            //

            //
            //
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.FileName =  Form1.AAC_Encoder;
            p.StartInfo.Arguments = string.Format(Form1.AAC_CommandLine, wavPathName, OutputFileName);
            //p.StartInfo.RedirectStandardOutput = true;
            //p.StartInfo.RedirectStandardError = true;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
            p.Start();
            //
            try
            {
                Utils.WindowToBackground(p.MainWindowHandle);
            }
            catch { }
            //output = p.StandardOutput.ReadToEnd();
            //output = p.StandardError.ReadToEnd();
            p.WaitForExit();
            iExitCode = p.ExitCode;
            p.Close();
            //


            TagLibConnector tgl = new TagLibConnector();
            //
            if (null != tgl)
            {
                //
                tgl.tagTrack = TrackNumber.ToString();
                tgl.tagTitle = Title;
                tgl.tagArtist = Author;
                tgl.tagAlbum = AlbumTitle;
                tgl.tagYear = Year.ToString();
                tgl.tagGenre = Genre;
                //
                if (tgl.WriteTags(OutputFileName))
                {
                    ;
                }
            }
            
            //
            if (DeleteInputFile)
            {
                File.Delete(wavPathName);
            }
            //
            return 0 == iExitCode;
        }
        //
        //
        //
        public bool IsEncoderOK()
        {
            if (!File.Exists(Form1.AAC_Encoder))
            {
                string foundEncoder = Utils.FindExecutable(Path.GetFileName(Form1.AAC_Encoder));
                if ("" == foundEncoder) return false;
                Form1.AAC_Encoder = foundEncoder;
            }
            return true;
        }
        //
        //
        // różnica o 1 w PlayTime najwyraźniej się zdarza
        // empiria - różnice o 1 są całkiem częste, teraz mam różnicę o 2
        private const int MaxDiferenceInTicks = 100;
        public bool IsOtputFileOK(int playTime)
        {
            //
            if (File.Exists(OutputFileName))
            {
                FileInfo fi = new FileInfo(OutputFileName);
                //
                if (0 == fi.Length) return false;
                //
                int nTicks = -1;
                if (Form1.mi.getPlayTimeForFile(OutputFileName, out nTicks))
                {
                    PlayTime = nTicks;
                }
                //
                //
                if ((-1 == playTime) || (-1 == PlayTime) || Math.Abs(playTime - PlayTime) > MaxDiferenceInTicks) return false;
                //
                //if (wmaFileLength > flacFileLength) return false;
                //
                /*
                long diff = Math.Abs(wmaFileLength - flacFileLength);
                if ((Math.Max(wmaFileLength, flacFileLength) / 5) < diff)// 20%
                {
                    return false;
                }
                */
                return true;
            }
            return false;
        }
        //
    }//class
}//namespace
